#include "gd32flash.h"
#include "modbus_slave.h"
extern VAR_T g_tVar;
uint16_t fmc_ReadWord(uint32_t faddr)
{
	return *(uint16_t*)faddr; 
}
void fmc_erase_and_program(uint8_t size)
{
    uint32_t *ptr = (uint32_t *)ERASE_PAGE_START_ADDR;
		int i;


    /* unlock the flash program/erase controller */
    fmc_unlock();

    /* clear all pending flags */
    fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_WPERR | FMC_FLAG_PGERR);

    /* erase target page */
    fmc_page_erase(ERASE_PAGE_START_ADDR);
    /* check the erase result, light the LED3 if the result is failed */
    if(0xFFFFFFFF != (*ptr)){
        gd_eval_led_on(LED3);

        return;
    }
		for(i=0;i<size;i++)
		{
			//datax=data[i];

			fmc_word_program(PROGRAM_ADDRESS+i*4, g_tVar.REG_Value[i]);

			// 
		}
    /* program target address */
    
    /* check the program result, light the LED3 if the result is failed */
    if(PROGRAM_DATA != (*ptr)){
        gd_eval_led_on(LED3);

        return;
    }

    /* light the LED4 if the erase and program result are both successful */
    gd_eval_led_on(LED4);

    /* clear all pending flags */
    fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_WPERR | FMC_FLAG_PGERR);

    /* lock the main FMC after the operation */
    fmc_lock();
}

void fmc_ReadContinusWord(uint32_t ReadAddr,uint16_t *pBuffer,uint16_t NumToRead)   	
{
	uint16_t i;
	for(i=0;i<NumToRead;i++)
	{
		pBuffer[i]=fmc_ReadWord(PROGRAM_ADDRESS+i*4);
	}
}